package cn.qyd.aqs;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 邱运铎
 * @date 2024-03-18 23:26
 */
public class ReentrantReadWriteLockDemo {
    public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public int data = 0;

    public void write(int value) {
        lock.writeLock().lock();
        try {
            data = value;
            System.out.println("写： " + Thread.currentThread().getName() + " : " + data);
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void read() {
        lock.readLock().lock();
        try {
            System.out.println("读： " + Thread.currentThread().getName() + " : " + data);
        } finally {
            lock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();

        Runnable readTask = () -> {
            for (int i = 0; i < 10; i++) {
                demo.read();
            }
        };
        Runnable writeTask = () -> {
          for (int i = 0; i < 10; i++) {
              demo.write(i);
          }
        };
        Thread readThread1 = new Thread(readTask);
        Thread readThread2 = new Thread(readTask);
        Thread writeThread = new Thread(writeTask);

        readThread1.start();
        readThread2.start();
        writeThread.start();

        try {
            readThread1.join();
            readThread2.join();
            writeThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
